<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>系统-用户</title>

    <link rel="stylesheet" href="../../plugins/fontawesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
    <link rel="stylesheet" href="../../plugins/icheck-bootstrap/icheck-bootstrap.min.css">
    <link rel="stylesheet" href="../../plugins/select2/css/select2.min.css">
    <link rel="stylesheet" href="../../plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">
    <link rel="stylesheet" href="../../adminLTE/css/adminlte.min.css">
    <link rel="stylesheet" href="../css/cloud.css">
    <style>
        .widget-user:hover .btn-grp-user {
            display: block;
        }

        .btn-grp-user {
            position: absolute;
            top: 5px;
            right: 10px;
            display: none;
        }

        .btn-user {
            margin-left: 5px;
            cursor: pointer;
        }

        .user-item-template {
            display: none;
        }

        .user-detail img {
            border: 3px solid #fff;
            height: auto;
            width: 90px;
            heighti: 90px;
            margin-top: 22px;
            margin-left: 22px;
        }
    </style>
</head>
<body class="content-wrapper" style="padding: 15px">
<!--顶部条-->
<div style="padding: 0 7px 15px 7px" class="clearfix">
    <!--搜索输入框组-->
    <div class="input-group pull-left" style="width: 50%">
        <input id="user-keyword" class="form-control" type="search" placeholder="用户名/姓名">
        <div class="input-group-append">
            <button id="user-search" class="btn btn-info btn-flat"><i class="fa fa-search"></i></button>
        </div>
    </div>
    <!--新增按钮-->
    <button id="user-add" class="btn btn-danger pull-right"><i class="fa fa-plus"></i> 新建用户</button>
</div>
<!--数据展示-->
<div class="container-fluid">
    <div class="row user-list">
        <!--数据实体-->
        <div class="col-md-4 user-item user-item-template" data-user-id="{{id}}">
            <div class="card card-widget widget-user">
                <!--数据操作按钮组-->
                <div class="btn-grp-user">
                    <span class="btn-user text-white user-modify" data-user-id="{{id}}" style="display: {{userModifyDisplay}}"><i class="fa fa-pencil"></i></span>
                    <span class="btn-user text-white user-remove" data-user-id="{{id}}" style="display: {{userRemoveDisplay}}"><i class="fa fa-close"></i></span>
                </div>
                <!--用户姓名和用户状态-->
                <div class="widget-user-header {{onlineClass}}">
                    <h3 class="widget-user-username">{{userName}}</h3>
                    <h5 class="widget-user-desc">{{onlineStatus}}</h5>
                </div>
                <!--用户头像-->
                <div class="widget-user-image">
                    <img class="img-circle elevation-2" src="{{image}}" alt="User Avatar">
                </div>
                <!--扩展信息-->
                <div class="card-footer">
                    <div class="row">
                        <!--用户名-->
                        <div class="col-sm-4 border-right widget-user-login-name">
                            <div class="description-block">
                                <h5 class="description-header">{{loginName}}</h5>
                                <span class="description-text">用户名</span>
                            </div>
                        </div>
                        <!--上次登录时间-->
                        <div class="col-sm-4 border-right widget-user-last-login-time">
                            <div class="description-block">
                                <h5 class="description-header">{{lastLoginDate}}</h5>
                                <span class="description-text">上次登录时间</span>
                            </div>
                        </div>
                        <!--上次登录IP-->
                        <div class="col-sm-4">
                            <div class="description-block widget-user-last-login-ip">
                                <h5 class="description-header">{{lastLoginIp}}</h5>
                                <span class="description-text">上次登录IP</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!--加载更多-->
<div class="text-sm-center text-gray user-more" style="display: none;">
    <span style="cursor: pointer"><i class="fa fa-hand-o-right"></i> 点击加载更多数据</span>
</div>
<!--正在加载-->
<div class="text-sm-center text-gray user-loading" style="display: none;">
    <span><i class="fa fa-refresh fa-spin"></i> 正在加载...</span>
</div>
<!--全部加载-->
<div class="text-sm-center text-gray user-complete" style="display: none;">
    <i class="fa fa-info-circle"></i> 已加载全部数据
</div>
<!--加载失败-->
<div class="text-sm-center text-gray user-error" style="display: none;">
    <i class="fa fa-exclamation-triangle"></i> 加载失败
</div>
<!--详情-->
<div class="side-panel right width400 bg-white hide user-detail">
    <div class="side-panel-btn bg-white" style="display: none"><i class="fa fa-chevron-right"></i></div>
    <div id="user-header" class="bg-info" style="height: 135px">
        <div class="pull-left">
            <div></div>
            <img id="user-image" class="img-circle elevation-2" src="../../adminLTE/img/avatar5.png" alt="User Avatar" style="cursor: pointer">
        </div>
        <div id="user-title" class="pull-left" style="padding: 30px">
            <h3>系统管理员</h3>
            <h5>在线</h5>
        </div>
    </div>
    <div class="progress progress-xxs bg-white">
        <div id="user-progress" class="progress-bar bg-danger" style="width: 0%"></div>
    </div>
    <div class="bg-white" style="padding:20px">
        <input type="hidden" id="user-id">
        <div class="form-group">
            <label for="user-name">姓名</label>
            <input type="text" class="form-control" id="user-name" placeholder="请填写用户姓名">
        </div>
        <div class="form-group">
            <label for="login-name">账号</label>
            <input type="text" class="form-control" id="login-name" placeholder="请填写用户账号">
        </div>
        <div class="form-group">
            <label for="login-name">密码</label>
            <input type="password" class="form-control" id="pass-word" placeholder="请填写密码">
        </div>
        <div class="form-group">
            <label for="roles">角色</label>
            <div class="select2-info">
                <select id="roles" class="select2" multiple="multiple" data-placeholder="请选择用户角色" data-dropdown-css-class="select2-info" style="width: 100%;"></select>
            </div>
        </div>
        <div class="form-group">
            <label for="tel">电话</label>
            <input type="tel" class="form-control" id="tel" placeholder="请填写联系电话">
        </div>
        <div class="bg-white">
            <button id="user-ok" class="btn btn-info">确定</button>
            <button id="user-cancel" class="btn btn-default">取消</button>
        </div>
    </div>
</div>

<input id="user-file" type="file" accept="image/gif, image/png, image/jpeg" style="display: none">

<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/select2/js/select2.full.min.js"></script>
<script src="../js/common.js"></script>
<script src="../js/child.js"></script>
<script>
    var AdminId = "adminId";

    var RoleControl = {
        roles: [],
        getRoles: function () {
            $.ajax({
                url: Url.baseService.rolePage,
                type: HttpMethod.get,
                headers: {pageSize: MaxPageSize, pageNumber: 1},
                success: function (result,status,xhr) {
                    RoleControl.roles = result.records;
                    RoleControl.setRoles();
                }
            })
        },
        setRoles: function () {
            var select2Datas = [];
            for (var i = 0; i < this.roles.length; i++) {
                var select2Data = {
                    id: RoleControl.roles[i].id,
                    text: RoleControl.roles[i].roleName
                };
                select2Datas.push(select2Data);
            }
            $("#roles").select2({ data: select2Datas });
        },
        getById: function (id) {
            var role;
            for (var i = 0; i < this.roles.length; i++) {
                if (this.roles[i].id === id) {
                    role = this.roles[i];
                    break;
                }
            }
            return role;
        },
        getByIds: function (ids) {
            var roles = [];
            for (var i = 0; i < this.roles.length; i++) {
                if (ids.indexOf(this.roles[i].id) >= 0) {
                    roles.push(this.roles[i]);
                }
            }
            return roles;
        },
        getIndex: function (roleId) {
            for (var i = 0; i < this.roles.length; i++) {
                if (this.roles[i].id === roleId) return i;
            }
            return undefined;
        },
        getIndexes: function (roleIds) {
            var indexs = [];
            for (var i = 0; i < roleIds.length; i++) {
                var index = this.getIndex(roleIds[i]);
                if (Utils.notEmpty(index)) indexs.push(index);
            }
            return indexs;
        }
    };

    var UserControl = {
        // 当前查询关键字
        keyword: "",
        // 当前查询页码
        pageNumber: 0,
        // 查询分页大小
        pageSize: 10,
        // 当前查询出来的所有用户，该数据和页面上展示的用户数量一致
        users: [],
        // 用户数据加载的html模板
        template: "",
        // 获取用户数据加载的html模板，并清空用户列表
        getTemplate: function () {
            this.template = $(".user-item-template").prop("outerHTML");
            $(".user-list").html("");
        },
        // 查询用户信息：查询关键字取keyword，查询页码为pageNumber+1
        // 查询成功后累加users数据并将pageNumber+1，然后重新绘制用户列表页面
        getUsers: function () {
            $.ajax({
                url: Url.baseService.userSearchByKeyword + "?keyword=" + this.keyword,
                type: HttpMethod.get,
                headers: {pageSize: UserControl.pageSize, pageNumber: UserControl.pageNumber + 1},
                success: function (result,status,xhr) {
                    UserControl.pageNumber++;
                    UserControl.users = UserControl.users.concat(result.records);
                    UserControl.setUsers();
                    var more = result.total > UserControl.pageNumber * UserControl.pageSize;
                    UserControl.setMore(more);
                }
            })
        },
        // 重新绘制用户列表页面
        setUsers: function () {
            $(".user-list").html("");
            for (var i = 0; i < this.users.length; i++) {
                var user = this.users[i];
                var lastLoginDate = Utils.isEmpty(user.lastLoginDate) ? "-" : user.lastLoginDate;
                var lastLoginIp = Utils.isEmpty(user.lastLoginIp) ? "-" : user.lastLoginIp;
                var onlineClass = Utils.isTrue(user.online) ? "bg-info" : "bg-gray";
                var image = Utils.isEmpty(user.image) ? "../../adminLTE/img/avatar5.png" :
                    Url.fileDownload.replace("{uuid}", user.image);
                var userModifyDisplay = user.id === AdminId ? "none" : "inline";
                var userRemoveDisplay = user.id === AdminId ? "none" : "inline";
                var userHtml = this.template
                    .replace(new RegExp("{{id}}", "gm"), user.id)
                    .replace(new RegExp("{{userName}}", "gm"), user.userName)
                    .replace(new RegExp("{{onlineStatus}}", "gm"), user.onlineStatus)
                    .replace(new RegExp("{{loginName}}", "gm"), user.loginName)
                    .replace(new RegExp("{{lastLoginDate}}", "gm"), lastLoginDate)
                    .replace(new RegExp("{{lastLoginIp}}", "gm"), lastLoginIp)
                    .replace(new RegExp("{{onlineClass}}", "gm"), onlineClass)
                    .replace(new RegExp("{{image}}", "gm"), image)
                    .replace(new RegExp("{{userModifyDisplay}}", "gm"), userModifyDisplay)
                    .replace(new RegExp("{{userRemoveDisplay}}", "gm"), userRemoveDisplay)
                    .replace(new RegExp("user-item-template", "gm"), "");
                $(".user-list").append(userHtml);
            }
        },
        // 绘制是否还有更多数据页面
        setMore: function (more) {
            if (more) {
                $(".user-more").show();
                $(".user-complete").hide();
            } else {
                $(".user-more").hide();
                $(".user-complete").show();
            }
            $(".user-loading").hide();
            $("#user-search").removeAttr("disabled");
        },
        // 绘制正在加载数据页面
        setLoading: function () {
            $(".user-more").hide();
            $(".user-complete").hide();
            $(".user-loading").show();
            $("#user-search").attr("disabled", "disabled");
        },
        // 按用户id到users中查询用户数据
        getById: function (id) {
            var user;
            for (var i = 0; i < this.users.length; i++) {
                if (this.users[i].id === id) {
                    user = this.users[i];
                    break;
                }
            }
            return user;
        },
        // 显示创建用户页面
        userCreate: function () {
            $("#user-header").removeClass("bg-info").removeClass("bg-gray").addClass("bg-gray");
            $("#user-image").attr("src", "../../adminLTE/img/avatar5.png");
            $("#user-title>h3").html("***");
            $("#user-title>h5").html("离线");
            $("#user-id, #user-name, #login-name, #pass-word, #tel").removeClass("is-invalid").removeClass("is-valid").removeClass("is-warning").val("");
            $("#pass-word").parent().show();
            $("#roles").attr("data-dropdown-css-class", "select2-info").val(null).trigger("change").parent().addClass("select2-info");
            $(".user-detail").removeClass("hide");
        },
        // 显示编辑用户页面并回显数据
        userModify: function (id) {
            this.userCreate();

            var user  = this.getById(id);
            $("#user-image").attr("src", Utils.isEmpty(user.image) ? "../../adminLTE/img/avatar5.png" : Url.fileDownload.replace("{uuid}", user.image));
            $("#user-title>h3").html(user.userName);
            $("#user-title>h5").html(user.onlineStatus);
            $("#user-id").val(user.id);
            $("#user-name").val(user.userName);
            $("#login-name").val(user.loginName);
            $("#pass-word").parent().hide();
            $("#tel").val(user.tel);

            var roleIds = [];
            for (var i = 0; i < user.roles.length; i++) {
                roleIds.push(user.roles[i].id);
            }
            $("#roles").val(roleIds).trigger("change");

            $(".user-detail").removeClass("hide");
        },
        // 校验输入的用户数据是否合法，合法返回user，否则返回undefined
        userValidate: function() {
            var id = $("#user-id").val();
            var user;
            if (Utils.isEmpty(id)) {
                user = {};
            } else {
                user = UserControl.getById(id);
            }
            user.userName = $("#user-name").val();
            user.loginName = $("#login-name").val();
            user.passWord = $("#pass-word").val();
            user.tel = $("#tel").val();
            user.roleIds = $("#roles").val();

            var validate = true;
            if (Utils.isEmpty(user.userName)) {
                $("#user-name").addClass("is-invalid");
                validate = false;
            } else {
                $("#user-name").addClass("is-valid");
            }
            if (Utils.isEmpty(user.loginName)) {
                $("#login-name").addClass("is-invalid");
                validate = false;
            } else {
                $("#login-name").addClass("is-valid");
            }
            if (Utils.isEmpty(user.tel)) {
                $("#tel").addClass("is-warning");
            } else {
                $("#tel").addClass("is-valid");
            }
            if (Utils.isEmpty(user.roleIds)) {
                $("#roles").attr("data-dropdown-css-class", "select2-danger").parent().addClass("select2-danger");
                validate = false;
            } else {
                $("#roles").attr("data-dropdown-css-class", "select2-info").parent().addClass("select2-info");
            }
            if (Utils.isEmpty(user.id) && Utils.isEmpty(user.passWord)) {
                $("#pass-word").addClass("is-invalid");
                validate = false;
            } else {
                $("#pass-word").addClass("is-valid");
            }

            if (validate) {
                return user;
            } else {
                return undefined;
            }
        },
        // 调用后端接口保存用户数据，成功后更新页面
        userSave: function () {
            var user = this.userValidate();
            if (Utils.isEmpty(user)) {
                return;
            }
            var doSave = function () {
                if (Utils.isEmpty(user.id)) {
                    $.ajax({
                        url: Url.baseService.userCreate,
                        type: HttpMethod.post,
                        contentType: ContentType.json,
                        data: JSON.stringify(user),
                        success: function (result,status,xhr) {
                            $(".user-detail").addClass("hide");
                            user = result;
                            user.online = false;
                            user.onlineStatus = "离线";
                            UserControl.users.push(user);
                            UserControl.setUsers();
                            parent.window.frameCtrl.toastr.success("用户创建成功！");
                        }
                    });
                } else {
                    $.ajax({
                        url: Url.baseService.userModify.replace("{id}", user.id),
                        type: HttpMethod.put,
                        contentType: ContentType.json,
                        data: JSON.stringify(user),
                        success: function (result,status,xhr) {
                            $(".user-detail").addClass("hide");
                            user = result;
                            var userIndex = UserControl.users.indexOf(user);
                            UserControl.users[userIndex] = user;
                            UserControl.setUsers();
                            parent.window.frameCtrl.toastr.success("用户修改成功！");
                        }
                    });
                }
            };
            var doUpload = function () {
                var files = $("#user-file").prop("files");

                var formdata = new FormData();
                formdata.append("multipartFile", files[0]);

                var xhr = new XMLHttpRequest();
                xhr.upload.onerror = function (ev) {
                    parent.window.frameCtrl.toastr.error("[" + xhr.status + "] " + xhr.responseJSON.error + ": " + xhr.responseJSON.message);
                    $("#user-progress").removeClass("bg-info").addClass("bg-danger")
                };
                xhr.upload.onprogress = function (ev) {
                    var per = Math.round(ev.loaded / ev.total * 100);
                    $("#user-progress").css("width", per + "%");
                };
                xhr.upload.onloadstart = function (ev) {
                    $("#user-progress").removeClass("bg-warning").removeClass("bg-danger").removeClass("bg-success")
                        .addClass("bg-info").css("width", "0%").parent().removeClass("bg-white");
                };
                xhr.upload.onload = function (ev) {
                    $("#user-progress").removeClass("bg-info").addClass("bg-success").css("width", "100%");
                };
                xhr.upload.onloadend = function (ev) {

                };
                xhr.onreadystatechange = function (ev) {
                    if (xhr.readyState === XMLHttpRequest.DONE) {
                        if (xhr.status === 200) {
                            if (Utils.isEmpty(user.image)) {
                                user.image = xhr.responseText;
                            }
                            doSave();
                        } else {
                            parent.window.frameCtrl.toastr.error("[" + xhr.status + "] " + xhr.responseJSON.error + ": " + xhr.responseJSON.message);
                        }
                    }
                };
                if (Utils.isEmpty(user.image)) {
                    xhr.open(HttpMethod.post, Url.fileCreate, true);
                } else {
                    xhr.open(HttpMethod.put, Url.fileModify.replace("{uuid}", user.image), true);
                }

                xhr.send(formdata);
                return xhr
            };

            doUpload();
        },
        // 调用后端接口删除用户数据，成功后更新页面
        userRemove: function (id) {
            $.ajax({
                url: Url.baseService.userRemove.replace("{id}", id),
                type: HttpMethod.delete,
                success: function (result,status,xhr) {
                    var user = UserControl.getById(id);
                    var userIndex = UserControl.users.indexOf(user);
                    UserControl.users.splice(userIndex, 1);
                    UserControl.setUsers();
                    parent.window.frameCtrl.toastr.success("用户删除成功！");
                }
            });

        }
    };

    var EventControl = {
        bind: function () {
            // 绑定修改按钮
            $(".user-list").on("click", ".user-modify", function () {
                var id = $(this).attr("data-user-id");
                UserControl.userModify(id);
            });
            // 绑定删除按钮
            $(".user-list").on("click", ".user-remove", function () {
                var id = $(this).attr("data-user-id");
                UserControl.userRemove(id);
            });
            // 绑定确定按钮
            $("#user-ok").bind("click", function () {
                var user = UserControl.userValidate();
                UserControl.userSave(user);
            });
            // 绑定取消按钮
            $("#user-cancel").bind("click", function () {
                $(".user-detail").addClass("hide");
            });
            // 新增按钮
            $("#user-add").bind("click", function () {
                UserControl.userCreate()
            });
            // 加载更多数据
            $(".user-more").bind("click", function () {
                UserControl.setLoading();
                UserControl.getUsers();
            });
            // 搜索用户数据
            $("#user-search").bind("click", function () {
                UserControl.setLoading();
                UserControl.keyword = $("#user-keyword").val();
                UserControl.users = [];
                UserControl.pageNumber = 0;
                UserControl.getUsers();
            });
            // 修改头像
            $("#user-image").bind("click", function () {
                $("#user-file").trigger("click");
            });
            // 预览头像
            $("#user-file").bind("change", function () {
                var files = $(this).prop("files");
                if (files.length === 0) {
                    return;
                }
                var file = files[0];
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onloadstart = function (ev) {
                    $("#user-image").attr("src", "../../adminLTE/img/loading.gif");
                };
                reader.onloadend = function (ev) {
                    $("#user-image").attr("src", ev.currentTarget.result);
                };
            });
            // 姓名变更
            $("#user-name").bind("change", function () {
                var userName = $(this).val();
                if (Utils.isEmpty(userName)) {
                    userName = "***";
                }
                $("#user-title>h3").html(userName);
            });
        }
    };

    UserControl.setLoading();
    UserControl.getTemplate();
    RoleControl.getRoles();
    UserControl.getUsers();
    EventControl.bind();
</script>
</body>
</html>